package com.fancon.android.gardenjokesx.activity;

import java.io.ByteArrayOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.apache.http.NameValuePair;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.Keys;
import com.fancon.android.gardenjokesx.social.TwitterSession;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask.IExcuteUi;
import com.fancon.android.gardenjokesx.utils.UserUtil;

public class S03_1Activity extends GardenJokesBaseActivity {

	private WebView webView;
	private TextView s03_1_2_3_4_7_title;
	private RelativeLayout topBar;

	public static Twitter mTwitter;
	public static TwitterSession mSession;
	public static AccessToken mAccessToken;
	private CommonsHttpOAuthConsumer mHttpOauthConsumer;
	private OAuthProvider mHttpOauthprovider;
	private String mConsumerKey;
	private String mSecretKey;
	private TwDialogListener mListener;	

	private static final String CALLBACK_URL = "twitterapp://connect";
	private static final String TAG = "TwitterApp";

	private String ver = "";
	private int screenID;
	private String userName;
	private String isSignIn;
	private Bundle bund;
	private int pre_screen_id;
	private String userIDTwitter;
	private Boolean isFirst = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s03_1_2_3_4_7);

		if (mSession != null) {
			if (mSession.getAccessToken() != null) {
				mAccessToken = null;
				mSession.resetAccessToken();
				mTwitter = null;
				Log.d("Reset Session Twitter", "Reset Session Twitter");
			}
		}
		try {
			// CookieSyncManager.createInstance(this);
			// CookieManager cookieManager = CookieManager.getInstance();
			// cookieManager.removeAllCookie();
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		if (getIntent().getExtras() != null) {
			bund = getIntent().getExtras();
			screenID = getIntent().getExtras().getInt(Constant.SCREEN_ID);
			pre_screen_id = getIntent().getExtras().getInt(
					Constant.PRE_SCREEN_ID);
			isSignIn = getIntent().getExtras().getString(Constant.IS_SIGNIN);
		}

		com.fancon.android.gardenjokesx.entity.User userID = new com.fancon.android.gardenjokesx.entity.User();
		userID = UserUtil.getInfoUserLogin(this);
		userName = userID.getUser_id();

		webView = (WebView) findViewById(R.id.s03_12347_webview);

		// set Text cho Title cua man hinh, twitter, weibo, facebook,...
		// set Backgroud cho Top Bar
		topBar = (RelativeLayout) findViewById(R.id.s03_12347_bg_top);
		s03_1_2_3_4_7_title = (TextView) findViewById(R.id.s03_12347_title);

		s03_1_2_3_4_7_title.setText(getString(R.string.s03_1_titler));
		topBar.setBackgroundResource(R.drawable.s03_1_top);

		// Khoi tao de dang ky tren twitter
		mTwitter = new TwitterFactory().getInstance();
		mSession = new TwitterSession(getApplicationContext());

		mConsumerKey = Keys.TWITTER_CONSUMER_KEY;
		mSecretKey = Keys.TWITTER_CONSUMER_SECRET;

		mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey,
				mSecretKey);
		mHttpOauthprovider = new DefaultOAuthProvider(
				"http://twitter.com/oauth/request_token",
				"http://twitter.com/oauth/access_token",
				"http://twitter.com/oauth/authorize");
		mAccessToken = mSession.getAccessToken();
		isFirst = true;
		configureToken();
		authorize();

		Button s03_12347_btnDone = (Button) findViewById(R.id.s03_12347_btnDone);
		s03_12347_btnDone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				bund.putBoolean(Constant.LINK_STATE, false);
				finishAc();
			}
		});

	}

	@SuppressWarnings("deprecation")
	private void configureToken() {
		if (isFirst == true) {
			mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
			isFirst = false;
		}
		if (mAccessToken != null) {
			mTwitter.setOAuthAccessToken(mAccessToken);
		}
	}

	public void authorize() {
		new Thread() {
			@Override
			public void run() {
				String authUrl = "";
				int what = 1;

				try {
					authUrl = mHttpOauthprovider.retrieveRequestToken(
							mHttpOauthConsumer, CALLBACK_URL);

					what = 0;

					Log.d(TAG, "Request token url " + authUrl);
				} catch (Exception e) {
					Log.d(TAG, "Failed to get request token");

					e.printStackTrace();
				}

				mHandler.sendMessage(mHandler
						.obtainMessage(what, 1, 0, authUrl));
			}
		}.start();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				if (msg.arg1 == 1) {
					Toast.makeText(S03_1Activity.this.getApplicationContext(),
							"Error getting request token == 1",
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(S03_1Activity.this.getApplicationContext(),
							"Error getting access token != 1",
							Toast.LENGTH_LONG).show();
				}
			} else {
				if (msg.arg1 == 1) {
					RequestTwitter((String) msg.obj);
				} else {
					Log.v("Token", mAccessToken.getToken());
					Log.v("TokenSecret", mAccessToken.getTokenSecret());
					if (userName != null && userName.length() > 0) {
						registerLink(userName, "T", mAccessToken.getToken(),
								mAccessToken.getTokenSecret(), false);
					}
					if (screenID == Constant.A02_2
							|| (screenID == Constant.S06 && pre_screen_id == Constant.S01)) {
						Bundle b = new Bundle();
						if (screenID == Constant.S06) {
							b = getIntent().getExtras();
						}
						// @binhbt comment

						Intent intent = new Intent(getApplicationContext(),
								SignupActivity.class);
						intent.putExtras(b);
						intent.putExtra(Constant.SCREEN_ID, Constant.S03_1);
						intent.putExtra(Constant.TWITTER_ACCESS_TOKEN,
								mAccessToken.getToken());
						intent.putExtra(Constant.ACCESS_SECRET,
								mAccessToken.getTokenSecret());
						intent.putExtra(Constant.USERNAME_SOCIAL,
								mSession.getUsername());
						intent.putExtra(Constant.ABOUT,
								mSession.getDescription());
						intent.putExtra(Constant.TWITTER_USER_ID,
								mSession.getUserID());
						ClearCacheWebview();
						startActivity(intent);
						finish();

					} else {
						DatabaseHelper db = new DatabaseHelper(
								S03_1Activity.this);
						db.addTwitterUser(userName, mAccessToken.getToken(),
								mAccessToken.getTokenSecret(),
								"TwitterServiceID", mSession.getUsername(), ver);
						db.close();
						bund.putBoolean(Constant.LINK_STATE, true);
						finishAc();
					}
				}
			}
		}
	};

	private void RequestTwitter(String url) {
		mListener = new TwDialogListener() {
			public void onComplete(String value) {
				processToken(value);
			}

			public void onError(String value) {
				Toast.makeText(S03_1Activity.this.getApplicationContext(),
						"Failed opening authorization page", Toast.LENGTH_LONG)
						.show();
			}
		};
		setUpWebView(url);
	}

	private void setUpWebView(String url) {
		try {
			webView.setVerticalScrollBarEnabled(false);
			webView.setHorizontalScrollBarEnabled(false);
			webView.getSettings().setJavaScriptEnabled(true);
			webView.getSettings().setAppCacheEnabled(false);
			webView.getSettings().setSavePassword(false);
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
			webView.setWebViewClient(new MyWebViewClient());
			webView.loadUrl(url);
			webView.requestFocus();
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d("Connect to Twitter", url);
			if (url.startsWith(CALLBACK_URL)) {
				if (url.startsWith(CALLBACK_URL + "?denied")) {
					bund.putBoolean(Constant.LINK_STATE, false);
					finishAc();
				} else {
					mListener.onComplete(url);
				}
				return true;
			} else {
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Log.d("Page error", description);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onPageFinished(WebView view, String url) {

			ClearCacheWebview();
		}

	}

	public void processToken(String callbackUrl) {

		final String verifier = getVerifier(callbackUrl);
		ver = verifier;
		Log.v("oauth_verifier", verifier);
		new Thread() {
			@Override
			public void run() {
				int what = 1;

				try {
					mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
							verifier);

					mAccessToken = new AccessToken(
							mHttpOauthConsumer.getToken(),
							mHttpOauthConsumer.getTokenSecret());

					configureToken();

					User user = mTwitter.verifyCredentials();
					userIDTwitter = Integer.toString(user.getId());
					mSession.storeAccessToken(mAccessToken,
							user.getScreenName(), user.getDescription(),
							String.valueOf(user.getId()));

					what = 0;
				} catch (Exception e) {
					Log.d(TAG, "Error getting access token");

					e.printStackTrace();
				}

				mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
			}
		}.start();
	}

	private String getVerifier(String callbackUrl) {
		String verifier = "";

		try {
			callbackUrl = callbackUrl.replace("twitterapp", "http");

			URL url = new URL(callbackUrl);
			String query = url.getQuery();

			String array[] = query.split("&");

			for (String parameter : array) {
				String v[] = parameter.split("=");

				if (URLDecoder.decode(v[0]).equals(
						oauth.signpost.OAuth.OAUTH_VERIFIER)) {
					verifier = URLDecoder.decode(v[1]);
					break;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		return verifier;
	}

	public interface TwDialogListener {
		public void onComplete(String value);

		public void onError(String value);
	}

	public void ClearCacheWebview() {
		try {
			S03_1Activity.this.deleteDatabase("webview.db");
			S03_1Activity.this.deleteDatabase("webviewCache.db");
			webView.clearHistory();
			webView.clearFormData();
			webView.clearCache(true);
			Log.v("Clear cache webview", "Clear success");
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	public void finishAc() {
		ClearCacheWebview();

		switch (screenID) {
		case Constant.S03:
			// @binhbt comment
			Intent ii = new Intent(S03_1Activity.this.getApplicationContext(),
					S03Activity.class);
			ii.putExtra(Constant.IS_SIGNIN, isSignIn);
			startActivity(ii);
			finish();
			break;

		case Constant.M01_1:
			Intent inten = getIntent();
			inten.putExtras(bund);
			setResult(RESULT_OK, inten);
			finish();
			break;

		case Constant.P06:
			Intent in = getIntent();
			in.putExtras(bund);
			Log.d("S03_1", "return: " + bund.getBoolean(Constant.LINK_STATE));
			setResult(RESULT_OK, in);
			finish();
			break;

		case Constant.M04_7:
			Intent intent = getIntent();
			intent.putExtras(bund);
			setResult(RESULT_OK, intent);
			finish();
			break;

		case Constant.S07:
			Intent inn = getIntent();
			inn.putExtras(bund);
			setResult(RESULT_OK, inn);
			finish();
			break;

		case Constant.S06:
			// @binhbt comment
			if (pre_screen_id == Constant.U02) {

				if (mAccessToken != null && mAccessToken.getToken() != null
						&& mAccessToken.getToken().length() > 0
						&& mAccessToken.getToken().length() > 0) {
					String imageProfileUrl ="";
					try {
						Log.d("S03_1",
								"Token: " + mAccessToken.getToken()
										+ ", Token Secret: "
										+ mAccessToken.getTokenSecret());
						User user = mTwitter.showUser(mTwitter.getId());
						URL url = user.getProfileImageURL();

						imageProfileUrl = url.getProtocol()
								+ "://"
								+ url.getHost()
								+ "/"
								+ (url.getPath() == null ? "" : url.getPath())
								+ (url.getQuery() == null ? "" : "?"
										+ url.getQuery());
					} catch (Exception e) {
						e.printStackTrace();
						// TODO: handle exception
					}
					// if (imageProfileUrl.length() > 0) {
					// Log.d("URL Profile", imageProfileUrl);
					// imageProfileUrl = imageProfileUrl.replace("_normal.",
					// "_bigger.");
					// Log.d("URL Profile", imageProfileUrl);
					// }

					// ImageLoader imageLoader = ((IMeshCache)
					// S03_1Activity.this)
					// .getmImgLoader();
					// imageProfileUrl = imageLoader
					// .getImageFromSD(imageProfileUrl);

					// Log.d("S03_1", "URL profile: " + imageProfileUrl);

					// @binint added
					IExcuteUi ie = new IExcuteUi() {

						@Override
						public void preExecute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void execute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void executeUI(String realPath) {
							// TODO Auto-generated method stub
							Log.d("S03_1", "URL profile: " + realPath);
							try {
								Bitmap bm = BitmapFactory.decodeFile(realPath);

								ByteArrayOutputStream bos = new ByteArrayOutputStream();
								bm.compress(CompressFormat.JPEG, 100, bos);
								byte[] data = bos.toByteArray();
								ByteArrayBody bad = new ByteArrayBody(data,
										"avatar.jpg");
								MultipartEntity reqEntity = new MultipartEntity();
								String user_id = UserUtil.getInfoUserLogin(
										S03_1Activity.this).getUser_id();

								reqEntity.addPart("image", bad);
								reqEntity.addPart("user_id", new StringBody(
										user_id));
								// @binhbt-comment
								// upload downloaded image to server
								// must use another thread to enhance process
								GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(
										S03_1Activity.this);
								String result = apiConnect.execPostImg(
										S03_1Activity.this,
										GardenJokesApiConnect.GROUP_S,
										"updateImageProfile", reqEntity);
								Log.d("S03_1", "post result: " + result);

								finish();
							} catch (Exception e) {
								e.printStackTrace();
								// TODO: handle exception
							}
						}

					};

					DownloadImageTask photoReq = new DownloadImageTask(
							"photo_rq", S03_1Activity.this, imageProfileUrl);
					photoReq.setIe(ie);
					getGlobalState().getRequestQueue().addRequest(photoReq);
					//

				}
			} else {
				finish();
			}
			break;

		case Constant.S04:
			// @binhbt comment

			Intent s04Intent = new Intent(S03_1Activity.this,
					S041Activity.class);
			s04Intent.putExtra(Constant.ID_BUTTON, "btnTwit");
			s04Intent.putExtra(Constant.SCREEN_ID, Constant.S03_1);
			startActivity(s04Intent);
			finish();

			break;

		default:
			finish();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		try {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				bund.putBoolean(Constant.LINK_STATE, false);
				finishAc();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return (super.onKeyDown(keyCode, event));
	}

	public void registerLink(String user_id, String type, String token,
			String secret, Boolean is_cancel) {
		String id = userIDTwitter;
		List<NameValuePair> request = new ArrayList<NameValuePair>(6);
		request.add(new BasicNameValuePair("user_id", user_id));
		request.add(new BasicNameValuePair("id", id));
		request.add(new BasicNameValuePair("type", type));
		request.add(new BasicNameValuePair("token", token));
		request.add(new BasicNameValuePair("secret", secret));
		if (is_cancel == false) {
			request.add(new BasicNameValuePair("is_cancel", "0"));
		} else {
			request.add(new BasicNameValuePair("is_cancel", "1"));
		}
		try {
			GardenJokesApiConnect api = new GardenJokesApiConnect(
					S03_1Activity.this);
			String req = api.execPost(getApplicationContext(),
					GardenJokesApiConnect.GROUP_S,
					"registerLinkToOtherServices", request);
			if (req != null && req.length() > 0) {
				Log.d("S03_1 registerLinkToOtherServices", req);
			}
		} catch (Exception e) {
		}

	}
}
